package lbframework.bean.tree;

import java.util.LinkedList;
import java.util.List;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class LBTreeModel implements TreeModel {

    public LBItemNode folderRoot = new LBItemNode("ROOT", 0);
    private static final List<TreeModelListener> listeners = new LinkedList<TreeModelListener>();

    public LBTreeModel() {
    }

    @Override
    public void addTreeModelListener(TreeModelListener l) {
        listeners.add(l);
    }

    @Override
    public Object getChild(Object parent, int index) {
        LBItemNode parentFB = (LBItemNode) parent;
        return parentFB.getChild(index);
    }

    @Override
    public int getChildCount(Object parent) {
        LBItemNode folder = (LBItemNode) parent;
        return folder.getChildCount();
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        LBItemNode parentFB = (LBItemNode) parent;
        for (int i = 0; i < parentFB.getChildCount(); i++) {
            if (child == parentFB.getChild(i)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public Object getRoot() {
        return folderRoot;
    }

    @Override
    public boolean isLeaf(Object node) {
        LBItemNode folder = (LBItemNode) node;
        return folder.getChildCount() == 0;
    }

    @Override
    public void removeTreeModelListener(TreeModelListener l) {
        listeners.remove(l);
    }

    /**
     * Called after the call to TreeCellEditor.getCellEditorValue(), passing the result of that method in the newValue parameter.
     */
    @Override
    public void valueForPathChanged(TreePath path, Object newValue) {
        LBItemNode folder = (LBItemNode) path.getLastPathComponent();
        folder.setSelecionado((Boolean) newValue == true ? 1 : 0);

        verificar(folderRoot);

        fireModelChangedEvent(path);
    }

    public void verificar(LBItemNode i_node) {
        double cont = 0;

        for (int i = 0; i < i_node.getChildCount(); i++) {
            LBItemNode oNode = i_node.getChild(i);

            verificar(oNode);

            if (oNode.getSelecionado() == 1) {
                cont++;
            } else if (oNode.getSelecionado() == 2) {
                cont += 0.5;
            }
        }

        if (cont > 0) {
            if (cont == i_node.getChildCount()) {
                i_node.selecionado = 1;
            } else {
                i_node.selecionado = 2;
            }
        } else {
            if (i_node.getChildCount() > 0) {
                i_node.selecionado = 0;
            }
        }
    }

    private void fireModelChangedEvent(TreePath path) {
        for (TreeModelListener l : listeners) {
            l.treeNodesChanged(new TreeModelEvent(this, path));
        }
    }
}